package demo.stack;

import java.util.Stack;

/**
 * 算数表达式求值
 * (1+(2+3)*(4*5))
 *
 */
public class Evalute {

    public static void main(String[] args) {
        String str = "(1+((2+3)*(4*5)))";
        String[] s = str.split("");

        Stack<String> ops = new Stack<String>();    //运算符栈
        Stack<Double> vals = new Stack<Double>();   //数字栈

        for (int i = 0; i < s.length; i++) {
            if (s[i].equals("(")) ;
            else if (s[i].equals("+")) ops.push(s[i]);
            else if (s[i].equals("-")) ops.push(s[i]);
            else if (s[i].equals("*")) ops.push(s[i]);
            else if (s[i].equals("/")) ops.push(s[i]);
            else if (s[i].equals("sqrt")) ops.push(s[i]); //sqrt 平方根函数
            else if (s[i].equals(")")) {
                String op = ops.pop();
                double v = vals.pop();
                if (op.equals("+")) v = vals.pop() + v;
                if (op.equals("-")) v = vals.pop() - v;
                if (op.equals("*")) v = vals.pop() * v;
                if (op.equals("/")) v = vals.pop() / v;
                if (op.equals("sqrt")) v = Math.sqrt(v);
                vals.push(v);
            }
            else vals.push(Double.parseDouble(s[i]));
        }
        System.out.println(vals.pop());
    }
}
